package top.fkxuexi.blogapi.core.config.shiro;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import top.fkxuexi.blogapi.core.utils.common.Code;
import top.fkxuexi.blogapi.core.utils.common.Result;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 权限验证失败的过滤器
 */
public class ShiroPermissionFilter extends PermissionsAuthorizationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String header = httpServletRequest.getHeader("X-Requested-With");
        boolean isAjax = "XMLHttpRequest" == header;
        if (isAjax) {//如果是ajax返回指定格式数据
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json");
            //返回禁止访问json字符串
            httpServletResponse.getWriter().write(JSONObject.toJSONString(new Result(Code.NO_AUTH,false)));
        } else {
            //TODO  这个地方的重定向，后面需要修改
            httpServletResponse.sendRedirect("/403");
        }
        return false;
    }
}
